import React from 'react'
import {connect} from 'react-redux'
import '../game-room/components/Main/live/live.css'
import {withRouter} from "react-router-dom";
import {log} from "../../utils/commonfunc";
import {getBasketballGameDetailReq, getBasketballLiveDetailReq, getBasketballLiveStatusReq} from "../../apis/goApis";

class BasketballLive extends React.Component {

    constructor(props) {
        super(props)
        this.matchId = parseInt(this.props.match.params.gameId)
        this.quarterTexts = ['第一节', '第二节', '第三节', '第四节', '加时',]
        this.state = {
            liveStatusList: [],
            liveList: [],
            quarter: 0,
        }
        this.timerId = null
    }

    componentDidMount() {
        this.checkGameStarted()
            .then(started => started ? this.checkLiveStatus() : false)
            .then(status => status && this.getLiveDetail(status))
            .then(() => this.freshGameLive())
    }

    componentDidUpdate(prevProps, prevState, snapshot) {
        const game = this.props.game
        const prev = prevProps.game
        if (game.State !== prev.State) {
            this.checkLiveStatus()
            if (game.State === '已完赛') {
                this.clearFreshGameLive()
            }
        }
    }

    componentWillUnmount() {
        this.clearFreshGameLive()
    }

    checkGameStarted() {
        return getBasketballGameDetailReq({id: this.matchId})
            .then(res => res.data?.ok !== "未开赛")
    }

    checkLiveStatus() {
        return getBasketballLiveStatusReq({id: this.matchId})
            .then(res => {
                const statusList = res.data.ok || [0, 0, 0, 0, 0,]
                const index = statusList.filter(i => i === 1).length - 1
                this.setState({
                    liveStatusList: statusList,
                    quarter: index,
                })
                return statusList
            })
    }

    freshGameLive() {
        const game = this.props.game
        const end = game.State === '已完赛'
        const notStart = game.State === '未开赛'
        // const start = ["第一节", "第一节完", "第二节", "第二节完", "第三节", "第三节完", "第四节", "第四节完", "上半场", "上半场完", "下半场", "下半场完", "加时赛",].includes(game.State)

        if (end || notStart) {
            return
        } else {
            if (this.state.liveStatusList[this.state.quarter] === 1) {
                this.timerId = setInterval(() => {

                    let params = {
                        id: this.matchId,
                        jie: this.state.quarter + 1,
                    }
                    getBasketballLiveDetailReq(params).then((res) => {
                        const liveList = [...this.state.liveList]
                        liveList[this.state.quarter] = res.data.ok
                        this.setState({
                            liveList,
                        })
                    })
                }, 10000)
            }
        }
    }

    clearFreshGameLive() {
        if (this.timerId) {
            clearInterval(this.timerId)
        }
    }

    getLiveDetail(statusList) {
        let ps = []

        statusList.forEach((status, index) => {
            if (status === 1) {
                let params = {
                    id: this.matchId,
                    jie: index + 1,
                }
                ps.push(getBasketballLiveDetailReq(params))
            }
        })
        return Promise.all(ps).then(res => {
            let liveList = res.map(liveRes => (liveRes.data.ok))
            this.setState({
                liveList,
            })
        })
    }

    renderTeamScore(team, isHome) {
        return <div className='flex bg-white' style={{padding: '15px',}}>
            <div className='flex-1 flex-align-center'>
                <div className='team-dot'/>
                <span>{team.name}</span>
            </div>
            <div className='flex-2 flex-space-between-align-center'>
                {team.score.map((s, i) => <span className='flex-1 text-align-center' key={i}>{s}</span>)}
                <span className='flex-1 text-align-center'>{team.score.reduce((a, b) => a + b, 0)}</span>
            </div>
        </div>
    }

    render() {
        const stripStyle = {
            width: '54px',
            height: '1px',
            background: 'rgba(51,51,51,0.2)',
        }
        const game = this.props.game
        const {
            home, away,
        } = game
        const score = (

            <div>
                <div className='flex bg-white mg-b-1px' style={{padding: '6px 15px',}}>
                    <div className='flex-1' />
                    <div className='flex-2 flex-space-between-align-center'>
                        <span className='flex-1 gray-text text-align-center'>一</span>
                        <span className='flex-1 gray-text text-align-center'>二</span>
                        <span className='flex-1 gray-text text-align-center'>三</span>
                        <span className='flex-1 gray-text text-align-center'>四</span>
                        <span className='flex-1 gray-text text-align-center'>OT</span>
                        <span className='flex-1 gray-text text-align-center'>总分</span>
                    </div>
                </div>

                {home && this.renderTeamScore(home, true)}
                {away && this.renderTeamScore(away)}

            </div>
        )
        const title = (
            <div className='flex-center-align-center mg-t-24px'>
                <div style={stripStyle}/>
                <p
                    style={{
                        padding: '0 8px',
                        fontSize: '16px',
                        lineHeight: '22px',
                        color: '#333',
                    }}
                >文字直播</p>
                <div style={stripStyle}/>
            </div>
        )

        const quarterButtons = (
            <div className='flex-space-between-align-center mg-b-12px'>
                {this.state.liveList.map((list, index) => {
                    const q = this.state.quarter
                    const active = q === index
                    return <div
                        key={index}
                        className={active ? 'quarter-button quarter-button-active' : 'quarter-button'}
                        onClick={() => this.setState({quarter: index,})}
                    >
                        <span>{this.quarterTexts[index]}</span>
                    </div>
                })}
            </div>
        )

        const live = (
            <div>
                {this.state.liveList.length > 0 && this.state.liveList[this.state.quarter].map((data, index) => {
                    // log(data)
                    // {T: "8:03", Score: "16-12", Text: "布鲁克·洛佩兹 7英尺漂移投篮命中 (克里斯·米德尔顿 助攻)", Team: 1}
                    let time = data.T
                    if (data.T.includes('.')) {
                        let seconds = data.T.split('.')[0]
                        if (seconds < 10) {
                            time = `00:0${seconds}`
                        }
                        time =  `00:${seconds}`
                    }

                    return <div key={index} className='basketball-live-text-item'>
                        <div className='flex-space-between-align-center pd-l-r-10px mg-b-4px'>
                            <span className='gray-text'>
                                {this.quarterTexts[this.state.quarter] + time}
                            </span>
                            <span>
                                {data.Score}
                            </span>
                        </div>

                        <div className='bg-white pd-8px-12px'>
                            <span className='basketball-live-text-item-span'>{data.Text}</span>
                        </div>
                    </div>
                })}
            </div>
        )

        const notStartedLive = (
            <div className='bg-white text-align-center flex-center-align-center' style={{padding: '50px 0',}}>
                <span className='gray-text'>
                    比赛未开始
                </span>
            </div>
        )
        const notStarted = this.props.game.State === '未开赛'
        return <div>
            {score}
            {title}
            <div className='pd-16-px'>
                {notStarted ? null : quarterButtons}
                {notStarted ? notStartedLive : live}
            </div>
        </div>
    }
}
const mapState = state => ({
    game: state.game.currentGame,
})

export default connect(mapState,)((withRouter(BasketballLive)))